package ui;

import dao.StudentApplicationDao;
import dao.StudentScholarshipDao;
import model.Student;
import model.StudentScholarship;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.io.File;
import java.util.List;

/**
 * 学生奖学金申请面板
 */
public class ScholarshipApplyPanel extends JPanel {

    private final Student currentStudent; // 当前登录的学生对象
    private final JTable scholarshipTable; // 奖学金表格
    private final DefaultTableModel tableModel; // 表格数据模型

    private JTextField searchField; // 搜索输入框
    private JTextField gpaField; // 绩点输入框
    private JTextArea honorArea; // 荣誉描述输入框

    private JTextField filePathField; // 文件路径展示框
    private JButton uploadBtn; // 文件上传按钮

    private File selectedFile; // 学生选择的上传文件

    public ScholarshipApplyPanel(Student student) {
        this.currentStudent = student;
        setLayout(new BorderLayout());

        // ===== 北部：标题 =====
        JLabel title = new JLabel("奖学金申请", JLabel.CENTER);
        title.setFont(new Font("微软雅黑", Font.BOLD, 24));
        title.setForeground(new Color(255, 105, 180));
        add(title, BorderLayout.NORTH);

        // ===== 南部：搜索栏 =====
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        searchPanel.add(new JLabel("搜索奖学金:"));
        searchField = new JTextField(20);
        searchPanel.add(searchField);
        JButton btnSearch = new JButton("搜索");
        searchPanel.add(btnSearch);
        add(searchPanel, BorderLayout.SOUTH);

        // ===== 中部左侧：奖学金列表表格 =====
        String[] columns = {"奖学金名称", "申报要求"};
        tableModel = new DefaultTableModel(columns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格不可编辑
            }
        };
        scholarshipTable = new JTable(tableModel);
        scholarshipTable.setRowHeight(60);
        // 设置第二列使用多行文本渲染器
        scholarshipTable.getColumnModel().getColumn(1).setCellRenderer(new TextAreaRenderer());
        JScrollPane tableScroll = new JScrollPane(scholarshipTable);

        // ===== 中部右侧：填写申报信息 =====
        JPanel rightPanel = new JPanel(new GridBagLayout());
        rightPanel.setPreferredSize(new Dimension(320, 0));
        rightPanel.setBorder(BorderFactory.createTitledBorder("填写申请信息"));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 8, 8, 8);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // GPA输入
        gbc.gridx = 0; gbc.gridy = 0;
        rightPanel.add(new JLabel("绩点(GPA):"), gbc);
        gpaField = new JTextField();
        gbc.gridy = 1;
        rightPanel.add(gpaField, gbc);

        // 荣誉输入框
        gbc.gridy = 2;
        rightPanel.add(new JLabel("荣誉:"), gbc);
        honorArea = new JTextArea(6, 20);
        honorArea.setLineWrap(true);
        honorArea.setWrapStyleWord(true);
        JScrollPane honorScroll = new JScrollPane(honorArea);
        gbc.gridy = 3;
        gbc.fill = GridBagConstraints.BOTH;
        rightPanel.add(honorScroll, gbc);

        // 文件上传区域
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridy = 4;
        rightPanel.add(new JLabel("上传材料:"), gbc);

        filePathField = new JTextField();
        filePathField.setEditable(false);
        gbc.gridy = 5;
        rightPanel.add(filePathField, gbc);

        uploadBtn = new JButton("选择文件");
        gbc.gridy = 6;
        rightPanel.add(uploadBtn, gbc);

        // 提交按钮
        JButton applyBtn = new JButton("立即申报");
        applyBtn.setBackground(new Color(255, 105, 180));
        applyBtn.setForeground(Color.WHITE);
        applyBtn.setFocusPainted(false);
        gbc.gridy = 7;
        rightPanel.add(applyBtn, gbc);

        // ===== 中部整体布局 =====
        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.add(tableScroll, BorderLayout.CENTER);
        centerPanel.add(rightPanel, BorderLayout.EAST);
        add(centerPanel, BorderLayout.CENTER);

        // ===== 功能实现 =====
        loadScholarships(); // 初始加载奖学金列表

        // 搜索按钮点击事件
        btnSearch.addActionListener(e -> searchScholarships());

        // 上传文件按钮点击事件
        uploadBtn.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            int result = fileChooser.showOpenDialog(this);
            if (result == JFileChooser.APPROVE_OPTION) {
                selectedFile = fileChooser.getSelectedFile();
                filePathField.setText(selectedFile.getAbsolutePath());
            }
        });

        // 申报按钮点击事件
        applyBtn.addActionListener(e -> {
            int row = scholarshipTable.getSelectedRow();
            if (row == -1) {
                JOptionPane.showMessageDialog(this, "请先选择一项奖学金", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            String scholarshipName = tableModel.getValueAt(row, 0).toString();
            String gpa = gpaField.getText().trim();
            String honor = honorArea.getText().trim();

            if (gpa.isEmpty()) {
                JOptionPane.showMessageDialog(this, "请填写绩点(GPA)", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            String filePath = (selectedFile != null) ? selectedFile.getAbsolutePath() : null;

            // 构造申请理由
            String reason = "绩点: " + gpa + "\n荣誉: " + (honor.isEmpty() ? "无" : honor);

            StudentApplicationDao dao = new StudentApplicationDao();
            boolean success;

            if (filePath != null) {
                // 包含文件路径的提交
                success = dao.submitApplicationWithReasonAndFile(currentStudent.getStudentId(), scholarshipName, reason, selectedFile);
            } else {
                // 不包含文件路径
                success = dao.submitApplicationWithReason(currentStudent.getStudentId(), scholarshipName, reason);
            }

            if (success) {
                JOptionPane.showMessageDialog(this, "申报成功！");
                loadScholarships(); // 刷新数据
                gpaField.setText("");
                honorArea.setText("");
                filePathField.setText("");
                selectedFile = null;
                scholarshipTable.clearSelection();
            } else {
                JOptionPane.showMessageDialog(this, "不能重复申报或系统错误", "失败", JOptionPane.ERROR_MESSAGE);
            }
        });
    }

    /**
     * 加载所有奖学金到表格中
     */
    private void loadScholarships() {
        List<StudentScholarship> list = new StudentScholarshipDao().getAll();
        tableModel.setRowCount(0); // 清空旧数据
        for (StudentScholarship s : list) {
            tableModel.addRow(new Object[]{s.getName(), s.getCriteria()});
        }
    }

    /**
     * 根据关键词搜索奖学金
     */
    private void searchScholarships() {
        String keyword = searchField.getText().trim().toLowerCase();
        List<StudentScholarship> list = new StudentScholarshipDao().getAll();
        tableModel.setRowCount(0);
        for (StudentScholarship s : list) {
            if (s.getName().toLowerCase().contains(keyword)) {
                tableModel.addRow(new Object[]{s.getName(), s.getCriteria()});
            }
        }
    }

    /**
     * 自定义表格渲染器，用于多行文本换行显示
     */
    static class TextAreaRenderer extends JTextArea implements javax.swing.table.TableCellRenderer {
        public TextAreaRenderer() {
            setLineWrap(true);
            setWrapStyleWord(true);
            setOpaque(true);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                                                       boolean hasFocus, int row, int column) {
            setText(value == null ? "" : value.toString());

            int width = table.getColumnModel().getColumn(column).getWidth();
            setSize(width, Short.MAX_VALUE);
            int preferredHeight = getPreferredSize().height;
            if (table.getRowHeight(row) != preferredHeight) {
                table.setRowHeight(row, preferredHeight);
            }

            if (isSelected) {
                setBackground(new Color(255, 182, 193));
                setForeground(Color.BLACK);
            } else {
                setBackground(Color.WHITE);
                setForeground(Color.BLACK);
            }

            return this;
        }
    }
}
